package com.neolix.watch.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.neolix.watch.R;
import com.neolix.watch.util.Constant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/*当使用外部已经存在的数据库时，也可以用GreenDao
* 也在DaoGenerate model 中写entity
* 只是把 DaoMaster.java 中的 createAllTables dropAllTables 方法中不需要创建的表注释掉
* 然后使用下面的类即可访问和操作
* */
public class InfoDatabaseHelper extends SQLiteOpenHelper {

    private String dbName;
    private String db_path;
    private Context context;
    private SQLiteDatabase myDataBase;
    private static InfoDatabaseHelper instance;
    private DaoSession daoSession;

    public static synchronized InfoDatabaseHelper infoDatabaseHelper(Context context) throws IOException {
        if (instance == null)
            instance = new InfoDatabaseHelper(context, Constant.WATCH_BASE_DB_NAME);

        return instance;
    }

    public synchronized SQLiteDatabase getDatabase() {
        if (myDataBase == null) {
            String myPath = db_path + dbName;
            myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        }
        return myDataBase;
    }

    public synchronized void close() {
        super.close();
        if (myDataBase != null) {
            myDataBase.close();
            myDataBase = null;
        }
    }

    private InfoDatabaseHelper(Context context, String dbName) throws IOException {
        super(context, dbName, null, 1);
        this.dbName = dbName;
        this.context = context;
        db_path = "/data/data/" + context.getPackageName() + "/databases/";
        importIfNotExist();
    }

    private boolean checkExist() {
        String myPath = db_path + dbName;
        File dbFile = new File(myPath);
        return dbFile.exists();
    }

    /**
     * Creates a empty database on the system and rewrites it with your own
     * database.
     */
    public void importIfNotExist() throws IOException {
        boolean dbExist = checkExist();

        if (!dbExist) {
            // By calling this method and empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();

            try {
                copyDatabase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private void copyDatabase() throws IOException {
//        InputStream is = context.getAssets().open(dbName);

        InputStream is = context.getResources().openRawResource(R.raw.watchbase);
        OutputStream os = new FileOutputStream(db_path + dbName);

        byte[] buffer = new byte[4096];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
        os.flush();
        os.close();
        is.close();
        this.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

//    public synchronized void insertCity() {
//        getDaoSession();
//
//        Cursor cursor = myDataBase.rawQuery("select name from sqlite_master where type='table' order by name", null);
//        while (cursor.moveToNext()) {
//            //遍历出表名
//            String name = cursor.getString(0);
//            Log.i("System.out", name);
//        }
//        cursor.close();
//        CityDao cityDao = daoSession.getCityDao();
//        City entity = new City();
//        entity.setName("北京");
//        cityDao.insert(entity);
//    }
//
//    public synchronized void queryCity() {
//        CityDao cityDao = daoSession.getCityDao();
//        List<City> cities = cityDao.queryBuilder().list();
//    }
//
//    private void getDaoSession() {
//        if (daoSession == null) {
//            getDatabase();
//            DaoMaster daoMaster = new DaoMaster(myDataBase);
//            daoSession = daoMaster.newSession();
//        }
//    }
}